import { PrismaClient } from '@prisma/client'

// 创建Prisma客户端实例
const prisma = new PrismaClient({
  log: process.env.NODE_ENV === 'development' ? ['query', 'info', 'warn', 'error'] : ['error']
})

// 数据库连接测试
export const testConnection = async (): Promise<void> => {
  try {
    await prisma.$connect()
    console.log('✅ 数据库连接成功')
  } catch (error) {
    console.error('❌ 数据库连接失败:', error)
    throw error
  }
}

// 优雅关闭数据库连接
export const closeConnection = async (): Promise<void> => {
  await prisma.$disconnect()
  console.log('🔌 数据库连接已关闭')
}

// 导出prisma实例
export { prisma }

// 处理进程退出时的清理
process.on('beforeExit', async () => {
  await closeConnection()
})

process.on('SIGINT', async () => {
  await closeConnection()
  process.exit(0)
})

process.on('SIGTERM', async () => {
  await closeConnection()
  process.exit(0)
})
